package ar.com.ford.it.fullEconomics.persistence.dao;

import java.util.Collection;
import java.util.LinkedList;
import ar.com.ford.it.fullEconomics.persistence.dto.Teese04Paypolicy;
import ar.com.ford.it.fullEconomics.persistence.dto.Teese05Paypolvers;
import ar.com.ford.it.fullEconomics.persistence.dto.Teesg01Plant;
import ar.com.ford.it.fullEconomics.struct.PaymentPolicyDisplayStruct;
import ar.com.ford.it.webengine.persistence.PersistenceUtil;
import com.ford.it.logging.ILogger;
import com.ford.it.logging.LogFactory;
import com.ford.it.persistence.PersistenceException;
import com.ford.it.persistence.PersistenceManager;
import com.ford.it.persistence.Query;
import com.ford.it.persistence.Transaction;

public class PaymentPolicyDao extends Dao {
    private static final String CLASS_NAME = PaymentPolicyDao.class.getName();
    private static final ILogger log = LogFactory.getInstance().getLogger(
            CLASS_NAME);

    /**
     * busca las politicas de pago segun los criterios especificados buscando el
     * valor aprovado previo para cada version
     * 
     * @param findPayPolVers
     * @return
     * @throws PersistenceException
     */
    public Collection<PaymentPolicyDisplayStruct> findPaymentPolicies(
                                                                      Teese05Paypolvers findPayPolVers)
            throws PersistenceException {

        String METHOD_NAME = "findPaymentPolicies";
        log.entering(CLASS_NAME, METHOD_NAME);

        PersistenceManager pm = PersistenceUtil.getPersistenceManager();
        Query query = pm.newQuery("findPaymentPolicies",
                Teese05Paypolvers.class);
        query.setParameters(findPayPolVers, "all");
        Collection<PaymentPolicyDisplayStruct> result = new LinkedList<PaymentPolicyDisplayStruct>();
        Collection<Teese05Paypolvers> payPolVersCol;

        payPolVersCol = (Collection) pm.executeQuery(query);

        for (Teese05Paypolvers payPolVers : payPolVersCol) {
            PaymentPolicyDisplayStruct dispPayPol = new PaymentPolicyDisplayStruct();
            dispPayPol.setDisplayVersion(payPolVers);
            Teese05Paypolvers prevPayPolVers = null;
            for (Teese05Paypolvers tempPayPolVers : payPolVersCol) {
                if (tempPayPolVers.getEese05PpyverApprovalUserC() != null) {
                    if (payPolVers.getTeese04Paypolicy()
                            .getEese04PaypolNumberK() == tempPayPolVers
                            .getTeese04Paypolicy().getEese04PaypolNumberK()) {
                        if (payPolVers.getEese05PpyverInDateY().getTime() > tempPayPolVers
                                .getEese05PpyverInDateY().getTime()) {
                            if (prevPayPolVers == null)
                                prevPayPolVers = tempPayPolVers;
                            else if (prevPayPolVers.getEese05PpyverInDateY()
                                    .getTime() < tempPayPolVers
                                    .getEese05PpyverInDateY().getTime())
                                prevPayPolVers = tempPayPolVers;
                        }
                    }
                }
            }
            if (prevPayPolVers != null)
                dispPayPol.setPreviousValue(prevPayPolVers
                        .getEese05PpyverPercentP());
            result.add(dispPayPol);
        }
        log.exiting(CLASS_NAME, METHOD_NAME);
        return result;
    }

    /**
     * busca las versiones mas recientemente aprovadas segun el filtro
     * especificado y el valor aprovado previo para cada una.
     * 
     * @param findPayPolVers
     * @return
     * @throws PersistenceException
     */
    public Collection<PaymentPolicyDisplayStruct> findLastAprovedPaymentPolicies(
                                                                                 Teese05Paypolvers findPayPolVers)
            throws PersistenceException {

        String METHOD_NAME = "findLastAprovedPaymentPolicies";
        log.entering(CLASS_NAME, METHOD_NAME);

        PersistenceManager pm = PersistenceUtil.getPersistenceManager();
        Query query = pm.newQuery("findPaymentPolicies",
                Teese05Paypolvers.class);
        query.setParameters(findPayPolVers, "approvedOnly");
        Collection<PaymentPolicyDisplayStruct> result = new LinkedList<PaymentPolicyDisplayStruct>();
        Collection<Teese05Paypolvers> payPolVersCol;

        payPolVersCol = (Collection) pm.executeQuery(query);
        boolean notFound = true;

        for (Teese05Paypolvers payPolVers : payPolVersCol) {
            for (PaymentPolicyDisplayStruct temp : result) {
                if (temp.getDisplayVersion().getTeese04Paypolicy()
                        .getEese04PaypolNumberK() == payPolVers
                        .getTeese04Paypolicy().getEese04PaypolNumberK()) {
                    notFound = false;
                    if (temp.getDisplayVersion().getEese05PpyverInDateY()
                            .getTime() < payPolVers.getEese05PpyverInDateY()
                            .getTime()) {
                        temp.setDisplayVersion(payPolVers);
                    }
                }
            }
            if (notFound) {
                PaymentPolicyDisplayStruct dispPayPol = new PaymentPolicyDisplayStruct();
                dispPayPol.setDisplayVersion(payPolVers);
                result.add(dispPayPol);
            }
            notFound = true;
        }
        for (PaymentPolicyDisplayStruct payPolStruct : result) {
            Teese05Paypolvers prevPayPolVers = null;
            for (Teese05Paypolvers tempPayPolVers : payPolVersCol) {
                if (tempPayPolVers.getEese05PpyverApprovalUserC() != null) {
                    if (payPolStruct.getDisplayVersion().getTeese04Paypolicy()
                            .getEese04PaypolNumberK() == tempPayPolVers
                            .getTeese04Paypolicy().getEese04PaypolNumberK()) {
                        if (payPolStruct.getDisplayVersion()
                                .getEese05PpyverInDateY().getTime() > tempPayPolVers
                                .getEese05PpyverInDateY().getTime()) {
                            if (prevPayPolVers == null)
                                prevPayPolVers = tempPayPolVers;
                            else if (prevPayPolVers.getEese05PpyverInDateY()
                                    .getTime() < tempPayPolVers
                                    .getEese05PpyverInDateY().getTime())
                                prevPayPolVers = tempPayPolVers;
                        }
                    }
                }
            }
            if (prevPayPolVers != null)
                payPolStruct.setPreviousValue(prevPayPolVers
                        .getEese05PpyverPercentP());
        }

        log.exiting(CLASS_NAME, METHOD_NAME);
        return result;
    }

    /**
     * crea un nuevo payment policy
     * 
     * @param payPolVers
     * @throws PersistenceException
     */
    public void createNewPayPolicy(Teese05Paypolvers payPolVers)
            throws PersistenceException {

        String METHOD_NAME = "createNewPayPolicy";
        log.entering(CLASS_NAME, METHOD_NAME);

        Transaction tx = null;

        tx = PersistenceUtil.getTransaction();
        tx.registerInsert(payPolVers);

        log.exiting(CLASS_NAME, METHOD_NAME);
    }

    /**
     * devuelve una version para ser actualizada
     * 
     * @param code
     * @param versionCode
     * @param plant
     * @return
     * @throws PersistenceException
     */
    public Teese05Paypolvers getPaymentPolicyVersionForUpdate(
                                                              Integer code,
                                                              Integer versionCode,
                                                              Teesg01Plant plant)
            throws PersistenceException {

        String METHOD_NAME = "getPaymentPolicyVersionForUpdate";
        log.entering(CLASS_NAME, METHOD_NAME);

        Teese05Paypolvers result = null;
        Teese05Paypolvers pk = new Teese05Paypolvers();
        Teese04Paypolicy payPol = new Teese04Paypolicy();

        payPol.setEese04PlantCodeC(plant);
        payPol.setEese04PaypolNumberK(code);

        pk.setEese05PpyverVersionNumberK(versionCode);
        pk.setTeese04Paypolicy(payPol);
        pk.setEese05PlantCodeC(plant);
        result = (Teese05Paypolvers) super.getObjForUpdate(pk);

        log.exiting(CLASS_NAME, METHOD_NAME);
        return result;
    }

    /**
     * devuelve la ultima version aprovada
     * 
     * @param payPolVers
     * @return
     * @throws PersistenceException
     */
    public Teese05Paypolvers getPrevAprovedVersion(Teese05Paypolvers payPolVers)
            throws PersistenceException {

        String METHOD_NAME = "getPrevAprovedVersion";
        log.entering(CLASS_NAME, METHOD_NAME);

        PersistenceManager pm = PersistenceUtil.getPersistenceManager();
        Query query = pm.newQuery("findPrevPaymentPolicy",
                Teese05Paypolvers.class);
        query.setParameters(payPolVers);
        Teese05Paypolvers result = null;

        result = (Teese05Paypolvers) pm.executeQuery(query);

        log.exiting(CLASS_NAME, METHOD_NAME);
        return result;
    }

    /**
     * verifica si el rango de fechas es valido
     * 
     * @param payPolVers
     * @return
     * @throws PersistenceException
     */
    public boolean validDateRange(Teese05Paypolvers payPolVers)
            throws PersistenceException {

        String METHOD_NAME = "getPrevAprovedVersion";
        log.entering(CLASS_NAME, METHOD_NAME);

        PersistenceManager pm = PersistenceUtil.getPersistenceManager();
        Query query = pm.newQuery("findPaymentPolicyInDateRange",
                Teese05Paypolvers.class);
        query.setParameters(payPolVers);
        Collection<Teese05Paypolvers> payPolInRange = null;
        boolean result = false;

        payPolInRange = (Collection) pm.executeQuery(query);

        if (payPolInRange.isEmpty())
            result = true;
        else
            result = false;

        log.exiting(CLASS_NAME, METHOD_NAME);
        return result;
    }

    /**
     * borra payPolVers
     * @param payPolVers
     * @throws PersistenceException
     */
    public void deletePaymentPolicyVersion(Teese05Paypolvers payPolVers)
            throws PersistenceException {

        String METHOD_NAME = "deletePaymentPolicyVersion";
        log.entering(CLASS_NAME, METHOD_NAME);

        Transaction tx = PersistenceUtil.getTransaction();
        if (tx != null) {
            tx.registerDelete(payPolVers);
        }

        log.exiting(CLASS_NAME, METHOD_NAME);
    }

}
